using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace GaDeTrung
{
    public partial class FormMain : Form
    {
        private Basket basket;
        private Random random;
        private System.Windows.Forms.Timer timerLay;
        private int diem = 0;
		public static List<Chicken> ListChicken = new List<Chicken>();
		public static List<Egg> ListEggs = new List<Egg>();
        // private Egg eggFalling;
        private int mang = 3;
        private int shit = 0;
        private int level = 0;
		// private Thread threadUpdate;
		struct POINTAPI
		{
			public Int32 x;
			public Int32 y;
		}
		struct MSG
		{
			public Int32 hwmd;
			public Int32 message;
			public Int32 wParam;
			public Int32 lParam;
			public Int32 time;
			public POINTAPI pt;
		}
 
		const Int64 FPS = 100;
		const Int64 FRAME_TIME = 1000 / FPS;

		[ DllImport( "user32.dll", SetLastError = true ) ]
		private static extern bool PeekMessage(
												ref MSG lpMsg,
												Int32 hwnd,
												Int32 wMsgFilterMin,
												Int32 wMsgFilterMax,
												PeekMessageOption wRemoveMsg);

		[ DllImport( "user32.dll", SetLastError = true ) ]
		private static extern bool TranslateMessage(ref MSG lpMsg);

		[ DllImport( "user32.dll", SetLastError = true ) ]   
		private static extern Int32 DispatchMessage(ref MSG lpMsg);
		
		[ DllImport( "user32.dll", SetLastError = true ) ]   
		private static extern void PostQuitMessage(int nExitCode);

		private enum PeekMessageOption
		{
		  PM_NOREMOVE = 0,
		  PM_REMOVE
		}

		private static Int32 WM_QUIT = 0x12;
		private static Int32 WM_DESTROY = 0x0002;
		//private static Int32 WM_CLOSE = 0x0010;

		public void Run()
		{
			MSG msg = new MSG();
			// Handle hwnd = this.Handle;

			while ( true )
			{
				if ( PeekMessage( ref msg, 0, 0, 0, PeekMessageOption.PM_REMOVE ) )
				{
					if ( msg.message == WM_QUIT || msg.message == WM_DESTROY )
					{
						PostQuitMessage(0);
						break;
					}

					TranslateMessage( ref msg );
					DispatchMessage( ref msg );
				}

				gameUpdate();

				// sleep a little
				// ts = new TimeSpan(0, 0, 0, 0, frameDiffMillis);
				System.Threading.Thread.Sleep(10);
			}
		}

        public FormMain()
        {
			// SetEventHandlers();
			this.KeyPreview = true;
			this.KeyPress += new KeyPressEventHandler(KeyPressEvent);
            InitializeComponent();
			this.Show();
			// threadUpdate = new Thread(gameUpdate);
			// threadUpdate.Name = "gameUpdate";
            //threadUpdate.IsBackground = true;
			// threadUpdate.Start();
        }        

        private void FormMain_Load(object sender, EventArgs e)
        {
			// tao mot dan ga gom 3 con
			for (int i = 0; i < 3; i++)
			{
                Chicken chicken = new Chicken();
                chicken.Top = 65;
                chicken.Left = i * (100 + 10) + 250;
                chicken.AddToParent(this);
				ListChicken.Add(chicken);
			}
			
            // tao random
            random = new Random();

            // tao mot timer
            timerLay = new System.Windows.Forms.Timer();
            timerLay.Interval = 5000;
            timerLay.Tick += new EventHandler(ChickenLayEgg);

            // tao mot cai ro
            basket = new Basket();
            basket.AddToParent(this);
            basket.Left = this.Width / 2 - 50;
            basket.Top = 495;

            // tao mot dan ga gom 3 con
            // for (int i = 0; i < 3; i++)
            // {
                // Chicken chicken = new Chicken();
                // chicken.Top = 50;
                // chicken.Left = i * (100 + 10) + 250;
                // chicken.AddToParent(this);
                
            // }
        }

        // private void CheckFail()
        private void gameUpdate()
        {
            // Int64 elapsedTimeMillis = DateTime.Now.Millisecond - currentFrameTimeMillis;
            // if (currentFrameTimeMillis < 0 || elapsedTimeMillis > FRAME_TIME)
            // {
            // currentFrameTimeMillis = DateTime.Now.Millisecond;
            // }
            // else
            // {
            // frameDiffMillis = (Int32)(FRAME_TIME - elapsedTimeMillis);
            // return;
            // }
            // Egg eggFalling = ListEggs[i];
            if (basket == null) return;
            this.Update();
            for (int i = ListEggs.Count - 1; i >= 0; i--)
            {
                // GaDeTrung.FormMain.ListEggs[i].UpdatePositionEgg();
                Egg eggFalling = ListEggs[i];
                int eggFallingBottom = eggFalling.Top + 48;
                int eggFallingRight = eggFalling.Left + 45;
                int basketBottom = basket.Top + 81;
                int basketRight = basket.Left + 100;

                eggFalling.UpdatePositionEgg();
                eggFalling.Draw();
                if (eggFallingBottom >= basket.Top)
                {
                    if (basket.Left < eggFalling.Left && eggFallingRight < basketRight)
                    {
                        // hung duoc trung
                        if (eggFalling.isEgg == true)
                        {
                            diem = diem + 5;
                            score.Text = Convert.ToString(diem);
                            score.BackColor = Color.Transparent;
                            score.ForeColor = Color.White;
                            level++;
                        }
                        else // hung trung shit 3 lan
                        {
                            shit++;
                            if (shit == 1) pictureBox4.BackgroundImage = Properties.Resources.shit;
                            if (shit == 2) pictureBox5.BackgroundImage = Properties.Resources.shit;
                            if (shit >= 3)
                            {
                                pictureBox6.BackgroundImage = Properties.Resources.shit;
                                shit = 0;
                                timerLay.Stop();
                                gameover.BackColor = Color.Transparent;
                                gameover.Text = "Game Over";
                            }
                        }
                    }
                    else
                    {
                        if (mang >= 0 && eggFalling.isEgg == true)
                            mang--;
                        if (mang == 2) pictureBox3.Hide();
                        if (mang == 1) pictureBox2.Hide();

                        if (mang <= 0)
                        {
                            pictureBox1.Hide();
                            this.timerLay.Stop();
                            this.gameover.BackColor = Color.Transparent;
                            this.gameover.Text = "Game Over";
                        }
                    }
					eggFalling.RemoveFromParent();
                    ListEggs.RemoveAt(i);
                }

                //tang do kho len
                if (level == 20)
                {
                    for (int j = ListEggs.Count - 1; j >= 0; j--)
                    {
                        ListEggs[i].Speed += 5;
                    }
                    //eggFalling.timerFall.Interval -= 20;
                }
            }
        }
        private void ChickenLayEgg(object sender, EventArgs e)
        {
            int r = random.Next(ListChicken.Count);
			Egg egg = new Egg();
			egg.Top = ListChicken[r].Top + 88;
			egg.Left = ListChicken[r].Left;
            egg.AddToParent(this);
            ListEggs.Add(egg);
        }
		
		void KeyPressEvent(object sender, KeyPressEventArgs e)
		{
			for (int i = 0; i < ListChicken.Count; i++)
			{
				// MessageBox.Show("aaaaaaaaaaaa " + e.KeyChar.ToString());
				// score.Text = e.KeyChar.ToString();
				ListChicken[i].ChangeType((char)e.KeyChar);
			}
		}
       
        private void FormMain_MouseMove(object sender, MouseEventArgs e)
        {
            basket.Left = e.X;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            timerLay.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timerLay.Stop();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            About ab = new About();
            ab.ShowDialog();
        }

       
    }
}